﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;

namespace FtpCrawler
{
    public class FtpFileParserInWindowsStyle : IFtpFileParser
    {
        /// <summary>
        /// 解析Windows格式的FTP文件列表
        /// </summary>
        /// <param name="line"></param>
        /// <returns></returns>
        public FtpFileInfo ParseFile(string line, string path)
        {
            try
            {
                FtpFileInfo fileInfo = new FtpFileInfo();
                fileInfo.Path = path;
                string str = line.Trim();
                string strDate = str.Substring(0, 8);
                str = (str.Substring(8, str.Length - 8)).Trim();
                string strTime = str.Substring(0, 7);
                str = (str.Substring(7, str.Length - 7)).Trim();

                fileInfo.ModifiedTime = this.GetModifiedTimeFromString(strDate + " " + strTime);

                if (str.Substring(0, 5) == "<DIR>")
                {
                    fileInfo.IsFile = false;
                    str = (str.Substring(5, str.Length - 5)).Trim();
                }
                else
                {
                    string[] arStr = str.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    fileInfo.IsFile = true;
                    str = arStr[1];
                }
                fileInfo.Filename = str;

                return fileInfo;
            }
            catch (Exception ex)
            {
                // 文件解析失败，返回null
                return null;
            }
        }

        /// <summary>
        /// 从DOS字符串中获取日期时间对象
        /// 例：12-08-08 09:14AM
        /// </summary>
        /// <remarks>参考：CodeProject下的LightFTPClient项目中的LightFTPClient.Form1.parseDosData(string text)</remarks>
        /// <param name="strDateTime"></param>
        /// <returns></returns>
        private DateTime GetModifiedTimeFromString(string strDateTime)
        {
            int month, day, year;
            month = int.Parse(strDateTime.Substring(0, 2));
            day = int.Parse(strDateTime.Substring(3, 2));
            year = 2000 + int.Parse(strDateTime.Substring(6, 2));　　// 21世纪
            if (year > DateTime.Now.Year)
            {
                year -= 100;    // 20世纪
            }

            int hour = int.Parse(strDateTime.Substring(9, 2));
            int minute = int.Parse(strDateTime.Substring(12, 2));
            string tt = strDateTime.Substring(14, 2);

            if (tt.ToUpper() == "PM")  // 下午
            {
                hour += 12;
                if (hour == 24)
                {
                    hour = 0;
                }
            }

            return new DateTime(year, month, day, hour, minute, 0);
        }
    }
}
